//
//  AudioPlayer.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-12.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "AudioPlayer.h"
#import "CollectionData.h"
#import "PlayerHistoryManager.h"
#import "DownloadManager.h"

@implementation AudioProgress

@end

@interface UIResponder (remote_control)

- (void)remoteControlReceivedWithEvent:(UIEvent *)event;

@end

@implementation UIResponder (remote_control)

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    [[AudioPlayer defaultPlayer] audio_remoteControlReceivedWithEvent:event];
}

@end

@implementation AudioPlayer

static AudioPlayer *audioPlayer;

+ (AudioPlayer *)defaultPlayer
{
    if (audioPlayer) {
        return audioPlayer;
    }
    audioPlayer = [[AudioPlayer alloc] init];
    return audioPlayer;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.playlist = [CollectionData getArrayData:kCollection_playing];
        _playingIndex = [[NSUserDefaults standardUserDefaults] integerForKey:kAudioPlayerHistoryIndex];
        if (_playingIndex < 0 || _playingIndex > _playlist.count - 1) {
            _playingIndex = 0;
        }
        _playerMode = [[NSUserDefaults standardUserDefaults] integerForKey:kAudioPlayerMode];
        
        progressTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkProgress) userInfo:nil repeats:YES] retain];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(streamerAudioPlayerStateDidChange) name:ASStatusChangedNotification object:nil];
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:nil];
        }
    }
    return self;
}

- (void)playlist:(NSArray *)listArray fromIndex:(int)index
{
    if (_running) {
        [self stop];
    }
    self.playlist = listArray;
    self.playingIndex = index;
    //添加到播放历史
    [[PlayerHistoryManager defaultManager] addPlaylist:self.playlist];
    [self play];

    NSString *plistName = [CollectionData getPlistName:kCollection_playing];
    NSDictionary *playingDictionary = [[[NSDictionary alloc] initWithObjectsAndKeys:self.playlist, plistName, nil] autorelease]; 
    // 本地保存正在播放的信息
    [CollectionData setCollections:playingDictionary type:kCollection_playing];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kPlayerStateDidChange object:nil];
}

- (void)play
{
    if (!_running) {//从头播放
        if (self.playlist.count == 0) {
            NSLog(@"无播放列表");
            return;
        }
        [self playIndex:_playingIndex];
        _running = YES;
    }
    else {//继续播放或者暂停
        [self pause];
    }
    [self stateDidChange];
}

- (void)stateDidChange
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kPlayerStateDidChange object:nil];
    switch ([self playerState]) {
        case AudioPlayerStatePlaying:
        {
            if (![progressTimer isValid]) {
                progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkProgress) userInfo:nil repeats:YES];
                [[NSRunLoop currentRunLoop] addTimer:progressTimer forMode:NSDefaultRunLoopMode];
            }
            [progressTimer fire];
            
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[AVAudioSession sharedInstance] setDelegate:self];
            
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            [self becomeFirstResponder];
            
            pausedByInterruption = NO;
        }
            break;
        case AudioPlayerStateStoped:
        {
            if ([progressTimer isValid]) {
                [progressTimer invalidate];
                progressTimer = nil;
            }
            
            [[AVAudioSession sharedInstance] setActive:NO error:nil];
            
//            [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
//            [self resignFirstResponder];
        }
            break;
        case AudioPlayerStateNone:
        {
            [[AVAudioSession sharedInstance] setActive:NO error:nil];
            
            [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
            [self resignFirstResponder];
        }
        default:
            break;
    }
}

- (void)checkProgress
{
    AudioProgress *progress = [[[AudioProgress alloc] init] autorelease];
    if (avAudioPlayer) {
        progress.lenght = avAudioPlayer.duration;
        progress.position = avAudioPlayer.currentTime;
    }
    else if (streamerAudioPlayer) {
        progress.lenght = streamerAudioPlayer.duration;
        progress.position = streamerAudioPlayer.progress;
    }
    else {
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kAudioProgressDidChange object:progress];
}

- (void)playIndex:(int)index
{
    NSDictionary *chapterInfo = [_playlist objectAtIndex:index];
    BOOL canPlay = [[chapterInfo objectForKey:@"read_flag"] boolValue];
    if (!canPlay) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kReadAuthorityFail object:nil];
        return;
    }
    [self stopPlaying];
    
    NSString *itemid = [chapterInfo valueForKey:@"item_id"];
    NSString *subitemid = [chapterInfo valueForKey:@"subitem_id"];
    
    if ([[DownloadManager defaultManager] isDownloaded:[chapterInfo valueForKey:@"subitem_id"]]) {
        avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:DownloadPath(itemid, subitemid)] error:nil];
        avAudioPlayer.delegate = self;
        if (historyFoward) {
            avAudioPlayer.currentTime = historyFowardTime;
            historyFoward = NO;
        }
        [avAudioPlayer play];
    }
    else {
        NSString *urlString = [[chapterInfo valueForKey:@"file_name"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        streamerAudioPlayer = [[AudioStreamer alloc] initWithURL:[NSURL URLWithString:urlString]];
        [streamerAudioPlayer start];
    }
    _playingIndex = index;
    [self indexDidChange];
}

- (void)indexDidChange
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kPlayerIndexDidChange object:nil];
    [[NSUserDefaults standardUserDefaults] setInteger:_playingIndex forKey:kAudioPlayerHistoryIndex];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)streamerAudioPlayerStateDidChange
{
    AudioStreamerState state = streamerAudioPlayer.state;
    NSLog(@">>>>>>streamerAudioPlayerStateDidChange:%d",state);
    
    switch (state) {
        case AS_STOPPED:
            //播放结束
            NSLog(@"播放结束");
            [self playNextByMode];
            break;
        case AS_PLAYING:
            NSLog(@"开始播放");
            if (historyFoward) {
                [streamerAudioPlayer seekToTime:historyFowardTime];
                historyFoward = NO;
            }
            break;
        case AS_STOPPING:
        {
            NSLog(@"播放终止");
            NSLog(@">>>>>>>>>>streamerAudioPlayer.errorCode:%d",streamerAudioPlayer.errorCode);
            switch (streamerAudioPlayer.errorCode) {
                case AS_NO_ERROR:
                    
                    break;
                case AS_NETWORK_CONNECTION_FAILED:
                {
                    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"连接失败，已暂停播放"] autorelease];
                    [promptView show];
                }
                default:
                {
                    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"未知错误，已暂停播放"] autorelease];
                    [promptView show];
                }
                    break;
            }
        }
        default:
            break;
    }
    
    [self stateDidChange];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (flag) {
        //播放结束
        [self playNextByMode];
    }
}

- (void)playNextByMode
{
    switch (_playerMode) {
        case AudioPlayerModeAllLoop:
            _playingIndex++;
            if (_playingIndex >= _playlist.count) {
                _playingIndex = 0;
            }
            break;
        case AudioPlayerModeSingleLoop:
            break;
        case AudioPlayerModeRandom:
            _playingIndex = arc4random() % _playlist.count;
        default:
            break;
    }
    [self playIndex:_playingIndex];
}

- (void)stop
{
    [self stopPlaying];
//    _playingIndex = 0;
    _running = NO;
    [self stateDidChange];
}

- (void)pause
{
    if ([avAudioPlayer isPlaying] || [streamerAudioPlayer isPlaying]) {
        if (avAudioPlayer) {
            [avAudioPlayer pause];
        }
        if (streamerAudioPlayer) {
            [streamerAudioPlayer pause];
        }
    }
    else {
        if (avAudioPlayer) {
            [avAudioPlayer play];
        }
        if (streamerAudioPlayer) {
            [streamerAudioPlayer pause];
        }
    }
    [self stateDidChange];
}

- (void)stopPlaying
{
    if (avAudioPlayer) {
        [avAudioPlayer stop];
        [avAudioPlayer release];
        avAudioPlayer = nil;
    }
    if (streamerAudioPlayer) {
        [streamerAudioPlayer stop];
        [streamerAudioPlayer release];
        streamerAudioPlayer = nil;
    }
    [self stateDidChange];
}

- (int)nextIndex
{
    if (_playingIndex+1 >= _playlist.count) {
        return -1;
    }
    return _playingIndex+1;
}

- (int)previousIndex
{
    if (_playingIndex-1 < 0) {
        return -1;
    }
    return _playingIndex-1;
}

- (void)playNext
{
    int index = [self nextIndex];
    if (index != -1) {
        [self stopPlaying];
        [self playIndex:index];
    } else {
        NSLog(@"到最后一个了");
    }
    [self stateDidChange];
}

- (void)playPrevious
{
    int index = [self previousIndex];
    if (index != -1) {
        [self stopPlaying];
        [self playIndex:index];
    } else {
        NSLog(@"到最开始一个了");
    }
    [self stateDidChange];
}

- (void)playAtTime:(float)percent
{
    if ([self playerState] != AudioPlayerStatePlaying) {
        [self play];
    }
    if (avAudioPlayer) {
        avAudioPlayer.currentTime = avAudioPlayer.duration * percent;
        NSLog(@"seek done:%f",avAudioPlayer.duration * percent);
    }
    else if (streamerAudioPlayer) {
        [streamerAudioPlayer seekToTime:streamerAudioPlayer.duration * percent];
        NSLog(@"seek done:%f",streamerAudioPlayer.duration * percent);
    }
}

- (void)setHistoryFowardTime:(float)time
{
    historyFoward = YES;
    historyFowardTime = time;
}

- (NSDictionary *)currentItem
{
    if (_playingIndex >= 0 && _playlist.count > _playingIndex) {
        return [_playlist objectAtIndex:_playingIndex];
    }
    return nil;
}

- (AudioPlayerState)playerState
{
    if (avAudioPlayer) {
        if (avAudioPlayer.playing) {
            return AudioPlayerStatePlaying;
        }
        else {
            return AudioPlayerStateStoped;
        }
    }
    else if (streamerAudioPlayer) {
        AudioStreamerState state = streamerAudioPlayer.state;
        if (state == AS_INITIALIZED || state == AS_STARTING_FILE_THREAD || state == AS_WAITING_FOR_DATA || state == AS_FLUSHING_EOF || state == AS_WAITING_FOR_QUEUE_TO_START || state == AS_PLAYING || state == AS_BUFFERING) {
            return AudioPlayerStatePlaying;
        }
        else if (state == AS_STOPPING || state == AS_STOPPED || state == AS_PAUSED ) {
            return AudioPlayerStateStoped;
        }
    }
    return AudioPlayerStateNone;
}

- (void)beginInterruption
{
    NSLog(@"播放被打断");
    if ([streamerAudioPlayer isPlaying]) {
        [streamerAudioPlayer pause];
        pausedByInterruption = YES;
        [self stateDidChange];
    }
}

- (void)endInterruption
{
    NSLog(@"打断已恢复");
    [self stateDidChange];
    //从暂停中恢复
    if (pausedByInterruption && ![streamerAudioPlayer isPlaying] && ![avAudioPlayer isPlaying]) {
        [self pause];
        pausedByInterruption = NO;
        [self stateDidChange];
    }
}

- (void)handleInterruption:(NSNotification *)notification
{
    switch ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] intValue]) {
        case AVAudioSessionInterruptionTypeBegan:
            [self beginInterruption];
            break;
        case AVAudioSessionInterruptionTypeEnded:
            [self endInterruption];
            break;
        default:
            break;
    }
}

- (void)audio_remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl) {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [self play];
                break;
            case UIEventSubtypeRemoteControlPause:
                [self play];
                break;
            case UIEventSubtypeRemoteControlStop:
                [self stop];
                break;
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [self play];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self playNext];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self playPrevious];
                break;
            default:
                break;
        }
    }
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_playlist release];
    [progressTimer release];
    [super dealloc];
}
@end
